'use strict';

import React from 'react';
import {
    Text,
    View,
    Image,
    NativeModules,
    TouchableHighlight,
    Modal,
    DeviceEventEmitter,
    NativeEventEmitter,
    Platform,
    Alert,
} from 'react-native';
import {naviPush, gotoView, naviReset} from '../../navigatorApp/actions';
import {connect} from 'react-redux'
import styles from './styles';
import CLNavigatorHeader from '../../component/CLNavigatorHeader'
import TabMain from './tab_main'
import TabMy from './tab_my'
import QRCode from 'react-native-qrcode';
import OrderList from '../order'
const {RNEvent} = NativeModules;
import TabNavigator from 'react-native-tab-navigator';
import {toast} from '../../utils/NativeUtil'
class Main extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            selectedTab: 'home',
            title: "首页",
            orderIndex: 0,
            shopImgModalVisible: false
        }
    }

    static navigationOptions = ({navigation, screenProps}) => {
        const {params = {}} = navigation.state;
        let header = (<CLNavigatorHeader leftItem={null} navigation={navigation} title={params.title}
                                         rightImage={params.rightImg}
                                         rightAction={() => params.rightQr()}
        />);
        return {header}
    };

    setTitle = (title) => {
        this.props.navigation.setParams({title: title});
    };

    setRightImage = (index) => {
        if (index == 0) {
            this.props.navigation.setParams({rightImg: require('../../image/icon_qr.png')})
        } else {
            this.props.navigation.setParams({rightImg: null})
        }
    };

    showQrImg = () => {
        if (this.isCanUse()) {
            let imgstate = this.state.shopImgModalVisible;
            this.setState({
                shopImgModalVisible: !imgstate
            })
        }
    };

    componentDidMount() {
        this.props.navigation.setParams({rightQr: this.showQrImg});
        this.setTitle("首页");
        this.setRightImage(0);
        this.emitter = Platform.OS == "ios" ? new NativeEventEmitter(RNEvent) : DeviceEventEmitter;
        const self = this;
        // this.subscription = this.emitter.addListener('GotoRoute', (values) => {
        //     const route = this.props.nav.routes[this.props.nav.routes.length - 1];
        //     if (route.routeName != "message") {
        //         self.props.naviPush("message");
        //     } else {
        //         toast("下拉查看最新消息")
        //     }
        // });
    }

    componentWillUnmount() {
        // this.subscription.remove();
        this.timer && clearTimeout(this.timer);
    }

    isCanUse = () => {
        if (this.props.shopState == 2) {
            return true;
        } else if (this.props.shopState == 3) {
            Alert.alert('提示',
                "您的店铺正在审核中",
                [
                    {
                        text: '了解', onPress: () => {
                    }
                    },
                ]);
        } else {
            let tsMessage = "";
            let buttonTitle = "";
            if (this.props.shopState == 0) {
                tsMessage = "请先创建店铺";
                buttonTitle = "立即创建";
            } else if (this.props.shopState == 1) {
                tsMessage = "请先完善店铺";
                buttonTitle = "立即完善";
            }
            Alert.alert('提示',
                tsMessage,
                [
                    {
                        text: '以后再说', onPress: () => {
                    }
                    },
                    {
                        text: buttonTitle, onPress: () => {
                        this.props.naviPush("shopComplete")
                    }
                    }
                ]);
            return false;
        }
    };

    onTabToOrder = () => {
        if (this.isCanUse()) {
            this.setTitle("我的订单");
            this.setState({selectedTab: 'order', title: "我的订单"});
        }
    };

    render() {
        let qrurl = "http://wap.tianyihui1688.com/shop/info" + "?" + "id=" + this.props.shopInfo.shopid + "&action=pay";
        qrurl = encodeURI(qrurl);
        return <View style={styles.containerView}>
            <TabNavigator>
                <TabNavigator.Item
                    key={1}
                    selected={this.state.selectedTab === 'home'}
                    title="首页"
                    titleStyle={styles.tabTextTitleDefault}
                    selectedTitleStyle={styles.tabTextTitleFoucs}
                    renderIcon={() => <Image resizeMode="contain" style={styles.tabItemImage}
                                             source={require('../../image/main_black.png')}/>}
                    renderSelectedIcon={() => <Image resizeMode="contain" style={styles.tabItemImage}
                                                     source={require('../../image/main_green.png')}/>}
                    onPress={() => {
                        this.setTitle("首页");
                        this.setRightImage(0);
                        this.setState({selectedTab: 'home', title: "首页"})
                    }}>
                    <TabMain />
                </TabNavigator.Item>
                <TabNavigator.Item
                    key={2}
                    selected={this.state.selectedTab === 'order'}
                    title="我的订单"
                    titleStyle={styles.tabTextTitleDefault}
                    selectedTitleStyle={styles.tabTextTitleFoucs}
                    renderIcon={() => <Image resizeMode="contain" style={styles.tabItemImage}
                                             source={require('../../image/order.png')}/>}
                    renderSelectedIcon={() => <Image resizeMode="contain" style={styles.tabItemImage}
                                                     source={require('../../image/order_f.png')}/>}
                    onPress={() => {
                        this.setRightImage(1);
                        this.onTabToOrder();
                    }}>
                    <OrderList orderIndex={this.state.orderIndex}/>
                </TabNavigator.Item>
                <TabNavigator.Item
                    key={3}
                    selected={this.state.selectedTab === 'my'}
                    title="我的"
                    titleStyle={styles.tabTextTitleDefault}
                    selectedTitleStyle={styles.tabTextTitleFoucs}
                    renderIcon={() => <Image resizeMode="contain" style={styles.tabItemImage}
                                             source={require('../../image/my_black.png')}/>}
                    renderSelectedIcon={() => <Image resizeMode="contain" style={styles.tabItemImage}
                                                     source={require('../../image/my_green.png')}/>}
                    onPress={() => {
                        this.setTitle("我的");
                        this.setRightImage(2);
                        this.setState({selectedTab: 'my', title: "我的"})
                    }}>
                    <TabMy />
                </TabNavigator.Item>
            </TabNavigator>

            <Modal
                transparent={true}
                visible={this.state.shopImgModalVisible}
                onRequestClose={() => this.showQrImg()}>
                <TouchableHighlight
                    underlayColor='rgba(255,255,255,0)'
                    style={{
                        flex: 1
                    }}
                    onPress={() => this.showQrImg()}>
                    <View
                        style={{
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            flex: 1,
                            flexDirection: 'column',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}>
                        <View style={{
                            borderRadius: 5,
                            flexDirection: 'column',
                            backgroundColor: 'white',
                            alignItems: 'center',
                            justifyContent: 'center',
                            width: 220,
                            height: 320
                        }}>
                            <Text
                                style={{
                                    marginTop: 20,
                                    fontStyle: 'italic',
                                    fontSize: 18,
                                    marginBottom: 20
                                }}>{this.props.shopInfo.shopname}</Text>
                            <QRCode
                                value={qrurl}
                                size={180}
                                bgColor='black'
                                fgColor='white'/>
                        </View>
                    </View>
                </TouchableHighlight>
            </Modal>

        </View>
    }
}


const mapStateToProps = state => ({
    shopState: state.mainmodel.shopState,
    token: state.mainmodel.token,
    nav: state.nav,
    shopInfo: state.mainmodel.shopInfo,
});

const mapDispatchToProps = dispatch => ({
    naviPush: (routeName) => {
        dispatch(naviPush(routeName))
    },
    naviReset: (index, routeName) => {
        dispatch(naviReset(index, routeName))
    },
    gotoView: (value) => {
        dispatch(gotoView(value))
    },
});

export default connect(mapStateToProps, mapDispatchToProps)(Main);

// export default Main;